package com.bigcms.controller;

import com.bigcms.domain.User;
import com.bigcms.service.UserService;
import com.bigcms.service.impl.UserServiceImpl;
import com.bigcms.utils.JWTUtils;
import com.bigcms.utils.JsonData;
import org.mockito.internal.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.provider.MD5;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("api/v1/pub/user")
public class PublicController {

    @Autowired
    UserService userService;

    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("reg")
    public JsonData reg(@RequestBody User user){
        if (!StringUtils.hasText(user.getMobile())){
            return JsonData.Error("请填写手机号");
        }
        if(!StringUtils.hasText(user.getPwd())){
            return JsonData.Error("请填写密码");
        }
        //用户是否存在
        User isHave = userService.getUser(user.getMobile());
        if(isHave!=null){
            return JsonData.Error("用户已存在");
        }
        //密码混淆
        String md5Password = DigestUtils.md5DigestAsHex(user.getPwd().getBytes());
        user.setPwd(md5Password);
        //时间混淆
        user.setCreateTime(new Date(new Date().getTime()));
        user.setUpdateTime(new Date(new Date().getTime()));
        int res = userService.addUser(user);
        if(res != 0){
            return JsonData.Success();
        }else{
            return JsonData.Error();
        }
    }

    /**
     * 登录
     * @param map
     * @return
     */
    @RequestMapping("login")
    public JsonData login(@RequestBody Map<String,String> map){
        if (!StringUtils.hasText(map.get("mobile"))){
            return JsonData.Error("请填写手机号");
        }
        User user = userService.getUser(map.get("mobile"));
        if(user==null){
            return JsonData.Error("用户不存在");
        }
        String md5Password = DigestUtils.md5DigestAsHex(map.get("pwd").getBytes());
        if(!user.getPwd().equals(md5Password)){
            System.out.println(md5Password);
            return JsonData.Error("密码错误");
        }
        //成功执行JWT
        String token = JWTUtils.geneJsonWebToken(user);
        Map<String,String> map1 = new HashMap<>();
        map1.put("token",token);
        //更新信息
        user.setUpdateTime(new Date());
        userService.editUser(user);
        return JsonData.Success(map1);
    }


}
